document.onkeydown = myKeyDownHandler;

function myKeyDownHandler(evt){
	if (evt.keyCode == 86){ //verb
		saveDefinition("verb")
	}
	else if (evt.keyCode == 65){ 
		saveDefinition("adjective")
	}
	else if (evt.keyCode == 68){ 		
		saveDefinition(null);
	}
	
	
}


/*function saveAndExit(){
	savePlease();
	allowSubmit();
	exit();
}*/

function saveDef(definition, type, range){
	//var checkout = "false";
	<!-- , checkout: checkout -->
	//var elems = reading.contentWindow.document.getElementsByClassName("pop_up");
//	for (i = 0; i < elems.length; i++){
	//	elems[i].style = "":
	//}
	//alert(text);
//	var loc = text.search("<div id=\"context_menu");
	//text = text.substr(0, loc);
	$.ajax({
  type: 'POST',
  url: "/user/readings/save_definition.jsp",
  data: {text: definition, id: id, type: type},
  success: function(msg) {
		var span = document.createElement('span');
		span.className = "def";
		range.surroundContents(span);
	//var saveButton = document.getElementById("save_button");
	//saveButton.disabled = true;
	//needsToBeSaved = false;
  },
  error:function(request,error){ alert("readyState: "+request.readyState +"\nstatus: "+request.status);
    alert("responseText: "+request.responseText); },
  dataType: "xml"
});
}
		
function enableButton(){
	var saveButton = document.getElementById("save_button");
	if (saveButton != null)
		saveButton.disabled = false;
	needsToBeSaved = true;
}
function getId(evt){
	return evt.target.id;
}

var edited_div;
function edit(evt){
	var span = reading.contentWindow.document.getElementById(evt.target.id);
	edited_div = reading.contentWindow.document.getElementById("d" + evt.target.id);
	
//	definitionDoc = definition.contentWindow.document;
	//definitionDoc.body.innerHTML = edited_div.innerHTML;
	$("#dialog").dialog({
		title: span.textContent,
		modal: true,
		buttons: { 
		"Cancel": function() { $(this).dialog("close"); },
		"Save": function() { $(this).dialog("close"); saveEdit();  }
		}
	});
			var definition = document.getElementById("definition");
			definitionDoc = definition.contentWindow.document;
			definitionDoc.designMode = "On";
			definitionDoc.body.innerHTML = edited_div.innerHTML;
			definition.contentWindow.focus();
	
	
/*	definitionDoc.designMode = "On";	
	var definition = document.getElementById("definition");
	definition.contentWindow.focus();*/
}

function saveEdit(){
	enableButton();
	edited_div.innerHTML = definitionDoc.body.innerHTML;
	//document.getElementById("grammar").selectedIndex;
	var genderIndex = document.getElementById("gender").selectedIndex;
	//alert(genderIndex);
//	definitionDoc.body.innerHTML = "";
}

var tip;

function showtip(evt) { 
	var id = getId(evt);
	//alert($(id).text());
	tip = reading.contentWindow.document.getElementById('d'+ id);

	var elem  = reading.contentWindow.document.getElementById(id);
	var par = elem.parentNode;
	showElement(tip, evt);
	showing = true;
}
function showTranslationTip(evt) { 
	var id = getId(evt);
	//alert($(id).text());
	tip = reading.contentWindow.document.getElementById('d'+ id);
	var elem = reading.contentWindow.document.getElementById(id);
	tip.style.visibility = "visible";
	tip.style.position = "absolute";

	tip.style.display = "block";
	var maxWidth = reading.contentWindow.document.width - elem.parentNode.offsetLeft;
	tip.style.maxWidth = maxWidth;	
	if (maxWidth > 300){
		tip.style.left = elem.parentNode.offsetLeft;
		tip.style.top 	= elem.parentNode.offsetTop + elem.parentNode.offsetHeight
	}
	else{
		tip.style.left = elem.offsetLeft + 10;
		tip.style.top = elem.offsetTop + 10;
	}

	//alert(tip.style.width);
	showing = true;
}


/*var wordRanges = new Array();
function processNode(elem){
	var textOfNode = elem.nodeValue;
	var	start =0;
	var wordBoundary = textOfNode.indexOf(" ");
	while (wordBoundary != -1){
		var range = doc.createRange();
		range.setStart(elem, start);
		range.setEnd(elem, optionObject.wordBoundary);
		wordRanges.push(range);
	}
	
}

function process(elem){
	var size = elem.childNodes.length;
	alert("innerHTML" + elem.innerHTML);
	alert(size);
	for (i = 0; i < size; i++){
		var child = elem.childNodes[i];
		if (child.nodeType == 3){
			processNode(child);
		}
		
	}
}
*/

function tryToExit(){
	if (needsToBeSaved){
		$("#confirmation").dialog({
			modal: true,
			buttons: { 
			"Cancel": function() { $(this).dialog("close"); },
			"Exit": function() { $(this).dialog("close"); exit(); }
			}
		});
	}
	else{
		exit();
	}
	//window.location = "/user/readings/reading_view.jsp?id=" + id;
}



function showElement(elem, evt){
	
	elem.style.left = evt.pageX  + 5;
	elem.style.top = evt.pageY  + 5;
	elem.style.display = "block";
	
}
function move(evt){
	tip.style.left = evt.pageX + 5;
	tip.style.top = evt.pageY + 5;
}

function hide(){
	tip.style.display = "none";
}

function positiontip(evt){
	if (showing){
		position(evt, tip, 10, 20);
	}
}

	var targetId;
	function deleteDiv(){
		enableButton();
		var span = reading.contentWindow.document.getElementById(targetId);
		var div = reading.contentWindow.document.getElementById(targetId);		

		if (span.className == "linked" || span.className == "translation" ){
			var textNode = reading.contentWindow.document.createTextNode(span.textContent);
			var parent = span.parentNode;
			parent.replaceChild(textNode, span);
			parent.normalize();
		}
	}

	function modifyDiv(){
		enableButton();
		var useroption = reading.contentWindow.window.getSelection();
		var range = getRangeObject(reading.contentWindow.window.document, useroption, false);
		if (range.startContainer != range.endContainer){
			alert("jiminey crickets" + range.startContainer.attributes.getAttribute("id"));
		}
		else{
			alert(range.startContainer.attributes.getAttribute("id"));
		}
	}

	function saveGrammarNoteDiv(){
		saveDiv("grammar");
	}
	
	function saveDefinitionDiv(){
		saveDiv("linked");
	}
	
	function saveTranslationDiv(){
		saveDiv("translation");
	}

	function saveDiv(className){
		enableButton();
		//var useroption = reading.contentWindow.window.getSelection();
		//var range = getRangeObject(reading.contentWindow.window.document, useroption);

		var def = definitionDoc.body.innerHTML;
		definitionDoc.body.innerHTML = "";
		var span = reading.contentWindow.document.createElement('span');
		span.className = className;
		span.setAttribute("id",  id);
		processElem(span, className);
		//alert(range.startOffset);
		//alert(range.endOffset);
		range.surroundContents(span);
	}
	
	function processElem(span, className){
		if (className != "translation"){
			span.onmouseover = function(event){ showtip(event)};
			span.onmousemove = function(event){ move(event)};
		}
		else{
			span.onmouseover = function(event){ showTranslationTip(event)};
		}
		
		span.onmouseout = function(event){ hide()};
		span.ondblclick = function(event){ edit(event)};
		span.oncontextmenu = function(event){ menu(event, "edit"); return false;};
	}



	function getRangeObject(optionObject) {
		if (optionObject.rangeCount > 0){
			 var range = optionObject.getRangeAt(0);
			 if (range == null){
				alert("range is null" + useroptionString);
			 }
			 return range;
		}
		else{
			alert("nothing is selected");
		}
		
	}

	function getNextId(){
		var counter = reading.contentWindow.document.getElementById("counter");
		if (counter == null){
			counter = reading.contentWindow.document.createElement("div");
			counter.setAttribute("id", "counter");
			counter.innerHTML = 1;
			//reading.contentWindow.document.getElementById("counter");
			reading.contentWindow.document.body.appendChild(counter);
		}
		else{
			counter.innerHTML = Math.floor(counter.innerHTML) + 1;	

		}
		return counter.innerHTML;
	}

function menu(evt, type){
	if (type == "edit"){
		targetId = evt.target.id;
		menuContent = "<ul><li><a href=\"javascript:parent.deleteDiv()\">Remove Definition</a></li></ul>";
	}
	else{
		menuContent = "<ul><li><a href=\"javascript:parent.addGrammarNote()\">Add Grammar Note</a></li><li><a href=\"javascript:parent.addDefinitionOrTranslation()\">Add Definition/Translation</a></li></ul>";
	}

	var menu = reading.contentWindow.document.getElementById("context_menu");
	menu.innerHTML = menuContent;
	menu.style.visibility = 'visible';
	
	menu.style.position = "absolute";

	
	//menu.style.top = 100;
		//	menu.style.left = 100;
			//alert(menu.style.top);
	//position(evt, menu, 2, 2);
	showElement(menu, evt);
	
	evt.cancelBubble = true;
	if (evt.stopPropagation) evt.stopPropagation();
	showingContextMenu = true;
	
//	var useroption = reading.contentWindow.window.getSelection();

	//var range = getRangeObject(reading.contentWindow.window.document, useroption);

}
var showingContextMenu = false;
function cancelContextMenu(){
	if (showingContextMenu){
		var menu = reading.contentWindow.document.getElementById("context_menu");
		menu.style.visibility = 'hidden';
		showingContextMenu = false;
	}
}

function textSelected(evt){
	alert("event" + evt);
}

var reading;
var definitionDoc;
function loaded(){
	document.onkeydown = keyevent;
	var save_button = document.getElementById("save_button");
	if (save_button != null)
		save_button.disabled = true;
	var text = document.getElementById("text");
	reading = document.getElementById("reading");
	//document.addEventListener('select', textSelected, false);
	var loc = text.innerHTML.search("<div id=\"context_menu");
	if (loc == -1){
		reading.contentWindow.document.body.innerHTML = text.innerHTML + "<div id=\"context_menu\"></div>";
	}
	else {
		reading.contentWindow.document.body.innerHTML = text.innerHTML;
	}
	var elems = reading.contentWindow.document.getElementsByClassName("linked");
	for (i = 0 ; i < elems.length; i++){
		processElem(elems[i], "linked");
	}
	
	elems = reading.contentWindow.document.getElementsByClassName("translation");
	for (i = 0 ; i < elems.length; i++){
		processElem(elems[i], "translation");
	}
	/*reading.contentWindow.onselect= function() {
	  alert('Handler for .select() called.');
	};*/
	var ss = reading.contentWindow.document.createElement("link");
	reading.contentWindow.document.oncontextmenu = function(event){ menu(event, "new"); return false;};
	reading.contentWindow.document.onclick = function(event){ cancelContextMenu(event);};
	
	ss.type = "text/css";
	ss.rel = "stylesheet";
	ss.href = "/readings/styles/docs.css";
	reading.contentWindow.document.getElementsByTagName("head")[0].appendChild(ss);
	var definition = document.getElementById("definition");
	definitionDoc = definition.contentWindow.document;
	definitionDoc.designMode = "On";
	
}
var title;
window.onload=loaded;

function saveDefinition(type){
	var useroption = window.getSelection();
	var useroptionString = useroption.toString();
	if (useroptionString.length > 0){		
		range = getRangeObject(useroption);
			// add definition
		title = useroptionString;
		saveDef(title, type, range);
	}
}

function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}

function trimEnd(str){
	if (str.substring(str.length - 1, str.length) == " "){
		return str.substring(0, str.length - 1);
	}
	return str;
}

function isPunctuationMark(selectedText){
	selectedText = trimEnd(selectedText);
	if (selectedText == '.' || selectedText == '?' || selectedText == '!'  || selectedText == ';'){
		return true;
	}
	else{
		 return false;
	}
}
/*function addTranslation(){
	var useroption = reading.contentWindow.window.getSelection();
	var useroptionString = useroption.toString();
	if (!isPunctuationMark(useroptionString)){
		alert("'translations' should be added to punctuation marks!");
	}
}*/

function addGrammarNote(){
	var useroption = reading.contentWindow.window.getSelection();
	var useroptionString = useroption.toString();
	title = useroptionString;
	if (useroptionString.length > 0){
		$("#dialog").dialog({
			modal: true,
			title: useroptionString,
			buttons: { 
			"Cancel": function() { $(this).dialog("close"); },
			"Save": function() { $(this).dialog("close"); saveGrammarNoteDiv();  }
			}
		});
		prepareForEditing()
	}
}

function prepareForEditing(){
	var definition = document.getElementById("definition");
	definitionDoc = definition.contentWindow.document;
	definitionDoc.body.innerHTML = "";
	definitionDoc.designMode = "On";
	definition.contentWindow.focus();
}